package com.mammoth.Bodybuilding.init;

import java.io.BufferedReader;import java.io.InputStreamReader;import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import com.mammoth.Bodybuilding.entity.RegionObj;
import com.mammoth.Bodybuilding.entity.SysMenu;
import com.mammoth.Bodybuilding.entity.SysRole;
import com.mammoth.Bodybuilding.entity.SysUserObj;
import com.mammoth.Bodybuilding.respository.IMenuRepository;
import com.mammoth.Bodybuilding.respository.IRegionRepository;
import com.mammoth.Bodybuilding.respository.IRoleRepository;
import com.mammoth.Bodybuilding.respository.IUserRepository;
import com.mammoth.Bodybuilding.util.ClientType;
import com.mammoth.Bodybuilding.util.MD5Util;
import com.mammoth.Bodybuilding.util.RoleType;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 
 * @title : ProjectINIT
 * @description : 项目初始化
 * @company : com.mammoth.Bodybuilding.util
 * @project Mammoth
 * @author xingzhaojun
 * @date 2018年4月24日 上午11:18:35
 */
@Component
public class ProjectINIT implements ApplicationRunner {

	/** 定义一个全局的记录器，通过LoggerFactory获取 **/
	private final static Logger logger = LoggerFactory.getLogger(ProjectINIT.class);

	/** 注入用户仓库 **/
	@Autowired
	private IUserRepository userRespository;

	/** 注入角色数据仓库 **/
	@Autowired
	private IRoleRepository roleRespository;

	/** 注入菜单数据仓库 **/
	@Autowired
	private IMenuRepository menuRespository;
	
	/** 注入地区数据仓库 **/
	@Autowired
	private IRegionRepository regionRespository;

	/** 读取json文件 **/
	@Value(value = "classpath:region.json")
	private Resource resource;
	
	/** 开发者用户 **/
	@Value(value = "${program.name}")
	private String programName;
	
	/** 开发者用户密码 **/
	@Value(value = "${program.password}")
	private String programPassword;
	
	
	/** 开发者用户邮箱 **/
	@Value(value = "${program.email}")
	private String programEmail;
	
	
	/** 开发者用户头像 **/
	@Value(value = "${program.headImg}")
	private String programHeadImg;

	@Override
	public void run(ApplicationArguments args) throws Exception {
		logger.info("校验初始化数据库信息...");
		/** 检查初始化 **/
		long count = roleRespository.count();
		if (count < 3) {
			logger.error("权限模块初始化信息不完全，正在补全。。。");
			List<SysRole> roles = new ArrayList<>();
			RoleType[] roleTemp = RoleType.values();
			for (RoleType roleType : roleTemp) {
				SysRole role = new SysRole(roleType.toString());
				roles.add(role);
			}
			roleRespository.saveAll(roles);
			logger.info("权限模块初始化信息保存成功");
		}
		/** 查找权限 **/
		SysRole role = roleRespository.findByRoleName(RoleType.ROLE_PROGRAM.toString());
		/** 设置开发者账户 **/
		logger.info("查询开发者账户是否存在...");
		Optional<SysUserObj> temp = userRespository.findByUsername("todd0722");
		if (!temp.isPresent()) {
			logger.error("开发者账户不存在。。。正在创建");
			SysUserObj user = new SysUserObj();
			user.setLoginName(programName);
			user.setPassword(MD5Util.encode(programPassword));
			user.setEmail(programEmail);
			/** 设置当前用户终端 **/
			user.setClientType(ClientType.PCMANAGETYPE.toString());
			/** 设置创建时间 **/
			user.setCreateTime(new Date());
			/** 设置默认头像 **/
			user.setHeadIMG(programHeadImg);
			user.setIntegral((long)0);
			user.setExperience((long)0);
			/** 设置权限 **/
			user.setSysRoles(role);
			user.setNickName("开发者账户");
			userRespository.save(user);
			logger.error("开发者账户创建完成");
		}
		/**检查开发者菜单是否存在**/
		boolean flag = true;
		List<SysMenu> menus = menuRespository.findAll();
		for (SysMenu sysMenu : menus) {
			List<SysRole> roles = sysMenu.getRole();
			if(roles.contains(role)){
				flag = false;
				break;
			}
		}
		if(flag) {
			SysRole adminRole = roleRespository.findByRoleName(RoleType.ROLE_ADMIN.toString());
			List<SysRole> roles = new ArrayList<>();
			SysMenu menu = new SysMenu();
			menu.setFid((long)0);
			menu.setMenuName("用户管理");
			roles.add(role);
			roles.add(adminRole);
			menu.setMenuPath("");
			menu.setRole(roles);
			menu.setSortNum(1);
			menu.setMenuFa("fa fa-user");
			SysMenu m = menuRespository.save(menu);
			menu = new SysMenu();
			menu.setFid(m.getId());
			menu.setMenuName("用户列表");
			menu.setMenuPath("/alluser");
			menu.setRole(roles);
			menu.setSortNum(1);
			menuRespository.save(menu);
			roles.remove(adminRole);
			menu = new SysMenu();
			menu.setFid((long)0);
			menu.setMenuName("菜单管理");
			menu.setMenuPath("");
			menu.setRole(roles);
			menu.setSortNum(2);
			menu.setMenuFa("fa fa-bars");
			SysMenu m1 = menuRespository.save(menu);
			menu = new SysMenu();
			menu.setFid(m1.getId());
			menu.setMenuName("菜单列表");
			menu.setMenuPath("/menu/allmenu");
			menu.setRole(roles);
			menu.setSortNum(1);
			menuRespository.save(menu);
		}
		
		/** 检查区域数据库初始化 **/
		count = regionRespository.count();
		if (count == 0) {
			logger.error("地区初始化信息不完全，正在补全。。。");
			List<RegionObj> regions = new ArrayList<>();

			BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream()));
			StringBuffer message = new StringBuffer();
			String line = null;
			while ((line = br.readLine()) != null) {
				message.append(line);
			}
			String defaultString = message.toString();
			String result = defaultString.replace("\r\n", "").replaceAll(" +", "");
			JSONObject json = JSONObject.fromObject(result);
			JSONArray jarr = json.getJSONArray("RECORDS");
			for (int i = 0; i < jarr.size(); i++) {
				JSONObject regionJson = jarr.getJSONObject(i);
				regions.add(new RegionObj(regionJson.getLong("id"), regionJson.getString("region_code"),
						regionJson.getString("region_name"), regionJson.getLong("fid"),
						regionJson.getString("region_name_en"), regionJson.getString("region_shortname_en"),
						regionJson.getString("level")));
			}
			regionRespository.saveAll(regions);
			logger.info("地区初始化信息保存成功");
		}
		logger.info("初始化校验完成，项目启动完成！");
	}

}
